import Mn from 'backbone.marionette';
import StatusLogEntryCollectionView from './StatusLogEntryCollectionView.js';
import StatusHistoryPopupView from "./StatusHistoryPopupView";
import StatusLogEntryFormPopupView from "./StatusLogEntryFormPopupView";
import StatusLogEntryModel from "../models/StatusLogEntryModel";


const StatusHistoryView = Mn.View.extend({
    tagName: 'div',
    className: function(){
        const baseClassNames = 'status_history hidden-print';
        if (this.collection && this.collection.length > 0) {
            return baseClassNames + ' memos';
        } else {
            return baseClassNames;
        }
    },
    template: require('./templates/StatusHistoryView.mustache'),
    regions: {
        comments: {
            el: '.comments',
            replaceElement: true,
        },
        'modalRegion': '.modalregion',
    },
    ui: {
      'show_all_btn': 'a.show_all',
      'add_new_btn': 'button.add_new',
    },
    events: {
        'click @ui.show_all_btn': 'onShowAll',
        'click @ui.add_new_btn': 'onAddNew',
    },
    childViewEvents: {
        'statuslogentry:edit': 'onEdit',
        'statuslogentry:show_full': 'onShowAll',
    },

    initialize(options){
        this.limitTo = 3;
        this.collection = options.collection;
        this.listenTo(this.collection, 'update', this.render.bind(this));
    },
    /**
     * @param focusedModel optional, the model to scroll to/focus within the collection
     */
    onShowAll(event, focusedModel){
        const view = new StatusHistoryPopupView({
            collection: this.collection,
            focusedModel: focusedModel,
        });
        this.showChildView('modalRegion', view);
    },
    onAddNew(){
      this.showChildView(
          'modalRegion',
          new StatusLogEntryFormPopupView({
              model: new StatusLogEntryModel(),
              destCollection: this.collection,
          }),
      );
    },
    onEdit(model){
      this.showChildView(
          'modalRegion',
          new StatusLogEntryFormPopupView({
              model: model,
              destCollection: this.collection,
              edit: true,
          }),
      );
    },
    onRender(){
        this.showChildView(
            "comments",
            new StatusLogEntryCollectionView({
                collection: this.collection,
                limitTo: this.limitTo,
            })
        );
        // className refresh is not done automatically at render-time by BB
        // force it
        this.$el.attr('class', this.className());
    },
    templateContext() {
        let hiddenItemCount = this.collection.length - this.limitTo
        return {
            limitTo: this.limitTo,
            hasHiddenItems: hiddenItemCount > 0,
            pluralize: hiddenItemCount > 1 ? 's' : '',
            hiddenItemsCount: hiddenItemCount,
            collectionLength: this.collection.length,
        }
    },
});
export default StatusHistoryView;
